<?php

namespace frontend\controllers;

use common\models\Collect;
use common\models\Type;
use Yii;
use common\models\Images;
use common\models\ImagesSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;

/**
 * ImagesController implements the CRUD actions for Images model.
 */
class ImagesController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    //详情页切换图片
    public  function  actionForMap($at,$id){

        $cache = Yii::$app->cache;
        $images = $cache->get('images');
        if ($images === false){
            $images = Images::find()->select(['id'])->asArray()->all();
            $cache->set('images',$images,3600);
            $images = $cache->get('images');
        }
        $suoyin = $cache->get('suoyin');
        if ($suoyin === false){
            foreach ($images as $k => $v){
                if ($id == $v['id']){
                    $cache->set('suoyin',$k,3600);
                    $suoyin = $cache->get('suoyin');
                    break;
                }
            }
        }


        $at == "right"?$xb = $suoyin+1 : $xb = $suoyin-1;
        $xb < 0 ? $xb = count($images)-1:$xb;
        $xb >= count($images) ? $xb = 0:$xb;
        $cache->set('suoyin',$xb,3600);
//        echo $cache->get('suoyin');exit;
        $this->redirect(['site/info','id'=>$images[$xb]['id']]);


    }

    public function actionCollect(){

        $id = Yii::$app->request->get('id');

        if (Yii::$app->user->isGuest) {
            Yii::$app->getSession()->setFlash('error', '<div style="text-align:center">你好歹登录一下嘛</div>');
            return $this->redirect(['site/info','id'=>$id]);
        }


        $uid = Yii::$app->user->getId();

        if(empty(Collect::find()->where(['images_id'=>$id,'user_id'=>$uid])->asArray()->all())) {
            Yii::$app->getSession()->setFlash('success', '<div style="text-align:center">已经收藏了啦</div>');
            return $this->redirect(['site/info','id'=>$id]);
        }

        $collect = new Collect();
        $collectdata['Collect'] = ['images_id'=>$id,'user_id'=>$uid,'collect_time'=>time()];//echo '<pre>';print_r($collectdata);exit;

        if($collect->load($collectdata) && $collect->save())
            Yii::$app->getSession()->setFlash('success', '<div style="text-align:center">收藏了啦</div>');
        else
            Yii::$app->getSession()->setFlash('error', '<div style="text-align:center">哎，怎么说呢，再来一次</div>');
        return $this->redirect(['site/info','id'=>$id]);
    }



    /**
     * Lists all Images models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new ImagesSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
//        echo im
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Images model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Images model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
//        if (!Yii::$app->user->can('createImg')){
////            throw new ForbiddenHttpException('不行啊');
//            Yii::$app->getSession()->setFlash('error', '你的权限不够的');
//            $this->goBack();return;
//        }

        $model = new Images();

        if (Yii::$app->request->post()) {
            $dir = date('Ymd', time());
            $path = Yii::$app->params['gaopinurl'] . '\\' . $dir;
            if (!file_exists($path)) {
                mkdir("$path", 0777, true);
            }
            //echo print_r(Yii::$app->request->post());exit();
            $model->url = UploadedFile::getInstance($model, 'url');
            $imgname = date('YmdHms', time()) . mt_rand(1000000000, 9999999999);

            $model->url->saveAs($path . '\\' . $imgname . '.' . $model->url->extension);
            $model->info = ($model->url->size / 1024 / 1024).'';
//            echo '<pre>'; echo $model->info;exit();
            $model->url = 'assets\upload\\' . $dir . '\\' . $imgname . '.' . $model->url->extension;
            $model->id = $imgname;
            $model->user_id = Yii::$app->user->id;
            $model->create_time = time();
            $model->load(Yii::$app->request->post());
            if($model->save())
                return $this->redirect(['site/info', 'id' => $model->id]);
            else
                return $this->redirect(['site/index']);
        } else {
            $typemodel = Type::find()->all();
            foreach ($typemodel as $k => $v) {
                $type[$v['id']] = $v['type_name'];
            }
            return $this->render('create', [
                'model' => $model,
                'typemodel' => $type,
            ]);
        }

    }

    /**
     * Updates an existing Images model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post())) {
            $dir = date('Ymd', time());
            $path = Yii::$app->params['gaopinurl'] . '\\' . $dir;
            if (!file_exists($path)) {
                mkdir("$path", 0777, true);
            }
            $model->url = UploadedFile::getInstance($model, 'url');
            $imgname = date('YmdHms', time()) . mt_rand(1000000000, 9999999999);
//            echo $model->url;exit;
            $model->url->saveAs($path . '\\' . $imgname . '.' . $model->url->extension);
            $model->info = ($model->url->size / 1024 / 1024) . 'MB';
//            echo '<pre>'; echo $model->info;exit();
            $model->url = 'assets\upload\\' . $dir . '\\' . $imgname . '.' . $model->url->extension;
            $model->save();
            return $this->redirect(['index', 'id' => $model->id]);
        } else {
            $typemodel = Type::find()->all();
            foreach ($typemodel as $k => $v) {
                $type[$v['id']] = $v['type_name'];
            }
            return $this->render('update', [
                'model' => $model,
                'typemodel' => $type,
            ]);
        }
    }

    /**
     * Deletes an existing Images model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Images model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Images the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Images::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
